<template>
  <basic-container>

    <avue-crud
      ref="crud"
      v-model="templateForm"
      :table-loading="Loading"
      :page.sync="page"
      :data="tableData"
      :option="tableOption"
      @on-load="onLoad"
      @refresh-change="onLoad"
      @row-save="handleSave"
      @row-update="handleUpdate"
      :before-close="beforeClose"
      :before-open="beforeOpen"
    >
      <template slot-scope="{type,size,row}" slot="menu">
        <el-button @click.stop="handleEdit(row)" icon="el-icon-upload" :size="size" :type="type">上传</el-button>
        <el-button @click.stop="rowDel(row)" icon="el-icon-view" :size="size" :type="type">查看文件</el-button>
        <el-button @click.stop="handleEdit(row)" icon="el-icon-s-tools" :size="size" :type="type">参数管理</el-button>
        <el-button @click.stop="rowDel(row)" icon="el-icon-sell" :size="size" :type="type">输入管理</el-button>
        <el-button @click.stop="handleEdit(row)" icon="el-icon-sold-out" :size="size" :type="type">输出管理</el-button>
        <el-button @click.stop="rowDel(row)" icon="el-icon-video-play" :size="size" :type="type">启用</el-button>
        <el-button @click.stop="handleEdit(row)" icon="el-icon-edit" :size="size" :type="type">编辑</el-button>
        <el-button @click.stop="rowDel(row)" icon="el-icon-delete" :size="size" :type="type">删除</el-button>
      </template>
      <template slot-scope="{}" slot="imgUrlLabel">
        <span style="color:#F56C6C;margin-right: 4px;">*</span><span>模板文件&nbsp;&nbsp;</span>
      </template>
      <template slot-scope="{row}" slot="imgUrlForm">
        <span v-if="isEdit">{{row.originalName}}</span>
        <el-upload
          class="upload-demo"
          ref="upload"
          :limit="1"
          :headers="headers"
          :data="uploadData"
          :action="url"
          :auto-upload="false"
          :on-success="successUpload"
          :on-exceed="moreFilesTip"
          :on-change="changeFile"
        >
          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        </el-upload>
      </template>
    </avue-crud>
  </basic-container>
</template>
<script>
  import website from '@/config/website';
  import {Base64} from 'js-base64';
  import {getToken} from '@/util/auth';
  import {
    getTemplateList,
    saveTemplate,
    updateTemplate,
    removeTemplate,
    saveUrl,
    updateUrl,
    downUrl,
    downLoadTemplate
  } from '@/api/dataMaintenance/fileTemplate';
  export default {
    data(){
      return {
        Loading:false,
        isEdit: false,
        fileList:[],
        previewVisible:false,
        tempType:'',
        imgUrl:'',
        url:'',
        saveUrl:saveUrl,
        updateUrl:updateUrl,
        downUrl:downUrl,
        uploadData: {
          attach:''
        },
        headers:{},
        templateForm:{},
        tableData: [],
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        tableOption: {
          index: true,
          //height: 'auto',
          //calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: false,
          editBtn: false,
          //addBtn: false,
          // viewBtn: true,
          delBtn: false,
          // menuWidth: 350,
          dialogClickModal: false,
          menuWidth: 280,
          column: [
            {
              label: '算子名称',
              prop: 'name',
              width: 140,
            },
            {
              label: '分类',
              prop: 'temType',
              type:'select',
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              dicUrl: '/api/blade-system/dict/dictionary?code=attach_type'
            },
            {
              label: '开发语言',
              prop: 'limitSize',
            },
            {
              label: '算子类型',
              prop: 'descr',
              display: false
            },
            {
              label: '启用状态',
              prop: 'status',
              width: 140,
              display: false
            },
            {
              label: '使用状态',
              prop: 'createUserName',
              display: false
            },
            {
              label: '修改时间',
              prop: 'updateTime',
              type: "date",
              format: "yyyy-MM-dd hh:mm:ss",
              width: 140,
              display: false
            },
          ]
        },
        file:null
      }
    },
    mounted() {
      this.setHeader();
    },
    methods: {
      beforeOpen(done,type) {
        if(type === 'add') {
          this.isEdit = false;
        } else {
          this.isEdit = true;
        }
        done();
      },
      beforeClose(done) {
        this.file = null;
        this.fileList = [];
        done();
      },
      changeFile(file, fileList) {
        console.log(file)
        this.file = file;
        this.isEdit = false;
      },
      moreFilesTip() {
        this.$message.error('只能选择一个文件');
      },
      setHeader() {
        this.headers['Authorization'] = `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}`;
        //让每个请求携带token
        this.headers[website.tokenHeader] = 'bearer ' + getToken();
      },
      onLoad(){
        this.getTemplateList();
        //this.tableData = createList();
      },
      getTemplateList() {
        this.Loading = true;
        getTemplateList({
          current: this.page.currentPage,
          size: this.page.pageSize
        }).then( res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.tableData = data.records;
          this.Loading = false;
        }).catch( error => {
          this.Loading = false;
        });
      },
      handleEdit(row) {
        this.fileList = [];
        this.fileList.push({
          'name':row['originalName']
        })
        this.$nextTick(function () {
          this.$refs.crud.rowEdit(row);
        })

      },
      handleUpdate(row, index, done, loading) {
        let obj = {
          id:row['id'],
          name:row['name'],
          temType: row['temType'],
          limitSize: row['limitSize'],
          descr: row['descr']
        };
        this.uploadData.attach = JSON.stringify(obj);

        if(this.$refs.upload.uploadFiles.length === 0 || this.$refs.upload.uploadFiles[0]['raw'] === undefined ) {
          const formData = new FormData();
          formData.append('attach',this.uploadData.attach);
          updateTemplate(formData).then( res => {
            this.getTemplateList();
            done();
          });
        } else {
          this.url = this.updateUrl;
          this.$nextTick(function () {
            let obj = {
              id:row['id'],
              name:row['name'],
              temType: row['temType'],
              limitSize: row['limitSize'],
              descr: row['descr']
            };
            this.uploadData.attach = JSON.stringify(obj);
            const formData = new FormData();
            formData.append('attach',this.uploadData.attach);
            formData.append('file', this.file.raw, this.file.name);
            updateTemplate(formData).then( res => {
              this.successUpload();
              done();
            });
            //this.$refs.upload.submit();
            done();
          });
        }


        // updateTemplate(obj).then( res => {
        //   this.getTemplateList();
        //   this.$message({
        //     type: "success",
        //     message: "操作成功!"
        //   });
        //   done();
        // }).catch( error => {
        //   loading();
        // });
      },
      handleSave(row,done,loading) {

        if(this.$refs.upload.uploadFiles.length === 0 ) {
          this.$message.error('请选择文件');
          loading()
          return;
        }

        this.url = this.saveUrl;
        this.$nextTick(function () {
          let obj = {
            name:row['name'],
            temType: row['temType'],
            limitSize: row['limitSize'],
            descr: row['descr']
          };
          this.uploadData.attach = JSON.stringify(obj);
          const formData = new FormData();
          formData.append('attach',this.uploadData.attach);
          formData.append('file', this.file.raw, this.file.name);
          saveTemplate(formData).then( res => {
            this.successUpload();
            done();
          });
        })
      },
      successUpload(res) {
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        this.getTemplateList();
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return removeTemplate(row.id);
          })
          .then(() => {
            this.getTemplateList();
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      downLoad(row){
        //window.open(`${this.downUrl}?id=${row['id']}`);
        downLoadTemplate({id:row['id']}).then( res => {
          const content = res.data
          const blob = new Blob([content])
          const file = row.originalName
          if ('download' in document.createElement('a')) {
            const elink = document.createElement('a')
            elink.download = file
            elink.style.display = 'none'
            elink.href = URL.createObjectURL(blob)
            this.imgUrl = URL.createObjectURL(blob);
            document.body.appendChild(elink)
            elink.click()
            URL.revokeObjectURL(elink.href)
            document.body.removeChild(elink)
          } else {
            navigator.msSaveBlob(blob, file)
          }
        });
      },
      preview(row) {
        this.tempType = row['temType'];
        downLoadTemplate({id:row['id']}).then( res => {
          const content = res.data
          const blob = new Blob([content])
          const file = row.originalName
          this.imgUrl = URL.createObjectURL(blob);
          this.previewVisible = true;
        });
      }
    }
  }
</script>
